#include "LUNA_WAVSound.h"
#include "Framework.h"

using namespace LUNA;

WAVSound::WAVSound( const std::string &filename ) :
ISound( "WAV" ),
mBuffer( 0 ),
mSource( 0 ),
mState( 0 )
{
	alGetError();
	alGenBuffers( 1, &mBuffer );
	
	if( !ALFWLoadWaveToBuffer( filename.c_str(), mBuffer ) )
	{
		THROW_RT("failed to load sound; name: " << filename);
	}
	
	alGenSources( 1, &mSource );
	alSourcei( mSource, AL_BUFFER, mBuffer );
}

WAVSound::~WAVSound()
{	
	alSourceStop( mSource );
    alDeleteSources( 1, &mSource );
	alDeleteBuffers( 1, &mBuffer );
}

void WAVSound::update()
{
}

SoundPlayState WAVSound::getPlayState() const
{
	ALint state = 0;
	alGetSourcei( mSource, AL_SOURCE_STATE, &state );

	switch( state )
	{
	case AL_INITIAL:
	case AL_STOPPED:
		return SPS_STOP;
		break;
	case AL_PAUSED:
		return SPS_PAUSE;
		break;
	case AL_PLAYING:
		return SPS_PLAY;
		break;
	}

	return SPS_NULL;
}

void WAVSound::setPlayState( SoundPlayState state )
{
	switch( state )
	{
		case SPS_PLAY:
			alSourcePlay( mSource );
			break;
		case SPS_PAUSE:
			alSourcePause( mSource );
			break;
		case SPS_STOP:
			alSourceStop( mSource );
			break;
		default:
			THROW_RT("bad play state");
			break;
	}
}

void WAVSound::setVolume( float volume )
{
	alSourcef( mSource, AL_GAIN, volume * getMasterVolume() );
}

void WAVSound::_setMasterVolume( float volume )
{
	mMasterVolume = volume;	
	alSourcef( mSource, AL_GAIN, volume * getMasterVolume() );
}